package com.jdd.modules.parking.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.*;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.system.vo.LoginUser;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.modules.configcartype.entity.ConfigCarType;
import com.jdd.modules.configcartype.service.IConfigCarTypeService;
import com.jdd.modules.parking.entity.ConfigParkThrough;
import com.jdd.modules.parking.service.IConfigParkThroughService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 车场通行配置
 * @Author: jdd
 * @Date: 2021-02-18
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "车场通行配置")
@RestController
@RequestMapping("/parking/configParkThrough")
public class ConfigParkThroughController {

    @Resource
    private IConfigParkThroughService configParkThroughService;
    @Resource
    private IConfigCarTypeService configCarTypeService;

    /**
     * 分页列表查询
     *
     * @param configParkThrough
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车场通行配置-分页列表查询")
    @ApiOperation(value = "车场通行配置-分页列表查询", notes = "车场通行配置-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ConfigParkThrough>> queryPageList(ConfigParkThrough configParkThrough,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, String startTime, String endTime,
                                                          HttpServletRequest req) {
        Result<IPage<ConfigParkThrough>> result = new Result<IPage<ConfigParkThrough>>();
        QueryWrapper<ConfigParkThrough> queryWrapper = QueryGenerator.initQueryWrapper(configParkThrough, req.getParameterMap());
        Page<ConfigParkThrough> page = new Page<ConfigParkThrough>(pageNo, pageSize);
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            queryWrapper.and(wrapper -> wrapper.ge("create_time", startTime + " 00:00:00").le("create_time", endTime + " 23:59:59"));
        }
        IPage<ConfigParkThrough> pageList = configParkThroughService.page(page, queryWrapper);
        for (int i = 0; i < pageList.getRecords().size(); i++) {
            ConfigParkThrough item = pageList.getRecords().get(i);
            String[] carTypeIds = item.getCarTypeId().split(",");
            StringBuilder carTypeNames = new StringBuilder();
            for (int o = 0; o < carTypeIds.length; o++) {
                ConfigCarType car = configCarTypeService.getById(carTypeIds[o]);
                if (car != null) {
                    if (o != 0) {
                        carTypeNames.append("/");
                    }
                    carTypeNames.append(car.getCarTypeName());
                }
            }
            item.setCarTypeId(carTypeNames.toString());
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param configParkThrough
     * @return
     */
    @AutoLog(value = "车场通行配置-添加")
    @ApiOperation(value = "车场通行配置-添加", notes = "车场通行配置-添加")
    @PostMapping(value = "/add")
    @OperationLogDetail(detail = "车场通行配置，添加", level = LogLevelType.ONE, operationType = OperationType.INSERT, operationUnit = OperationUnit.UNKNOWN)
    public Result<ConfigParkThrough> add(@RequestBody ConfigParkThrough configParkThrough) {
        Result<ConfigParkThrough> result = new Result<>();
        try {
            DateTime startTime = DateUtil.parse(configParkThrough.getStopStartTime(), "HH:mm:ss");
            DateTime endTime = DateUtil.parse(configParkThrough.getStopEndTime(), "HH:mm:ss");
            if (StringUtils.isNotBlank(configParkThrough.getStopWeeklyDay()) && DateUtil.compare(startTime,endTime) > 0){
                return result.error500("选择了禁止通行日的情况下，不允许跨天");
            }
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            configParkThrough.setCreateUser(sysUser.getUsername());
            configParkThrough.setId(SnowFlakeUtil.getId());
            configParkThroughService.saveEntity(configParkThrough);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param configParkThrough
     * @return
     */
    @AutoLog(value = "车场通行配置-编辑")
    @ApiOperation(value = "车场通行配置-编辑", notes = "车场通行配置-编辑")
    @PutMapping(value = "/edit")
    @OperationLogDetail(detail = "车场通行配置，编辑", level = LogLevelType.ONE, operationType = OperationType.UPDATE, operationUnit = OperationUnit.UNKNOWN)
    public Result<ConfigParkThrough> edit(@RequestBody ConfigParkThrough configParkThrough) {
        Result<ConfigParkThrough> result = new Result<>();
        ConfigParkThrough configParkThroughEntity = configParkThroughService.findById(configParkThrough.getId());
        if (configParkThroughEntity == null) {
            result.error500("未找到对应实体");
        } else {
            DateTime startTime = DateUtil.parse(configParkThrough.getStopStartTime(), "HH:mm:ss");
            DateTime endTime = DateUtil.parse(configParkThrough.getStopEndTime(), "HH:mm:ss");
            if (StringUtils.isNotBlank(configParkThrough.getStopWeeklyDay()) && DateUtil.compare(startTime,endTime) > 0){
                return result.error500("选择了禁行通知日的情况下，不允许跨天");
            }
            boolean ok = configParkThroughService.updateEntity(configParkThrough);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车场通行配置-通过id删除")
    @ApiOperation(value = "车场通行配置-通过id删除", notes = "车场通行配置-通过id删除")
    @DeleteMapping(value = "/delete")
    @OperationLogDetail(detail = "车场通行配置，通过id删除", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    public Result<?> delete(@RequestParam(name = "invateuserdetailId", required = true) String id) {
        try {
            configParkThroughService.deleteEntityById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "车场通行配置-批量删除")
    @ApiOperation(value = "车场通行配置-批量删除", notes = "车场通行配置-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @OperationLogDetail(detail = "车场通行配置，批量删除", level = LogLevelType.ONE, operationType = OperationType.DELETE, operationUnit = OperationUnit.UNKNOWN)
    public Result<ConfigParkThrough> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<ConfigParkThrough> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.configParkThroughService.deleteEntityByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车场通行配置-通过id查询")
    @ApiOperation(value = "车场通行配置-通过id查询", notes = "车场通行配置-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ConfigParkThrough> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ConfigParkThrough> result = new Result<>();
        ConfigParkThrough configParkThrough = configParkThroughService.findById(id);
        if (configParkThrough == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(configParkThrough);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 指定车场车辆类型列表查询
     *
     * @param
     * @return
     **/
    @AutoLog(value = "指定车场入口车道列表查询")
    @ApiOperation(value = "指定车场入口车道列表查询", notes = "指定车场入口车道列表查询")
    @RequestMapping(value = "/ParkThroughData")
    public Result<List<ConfigParkThrough>> parkThroughData(ConfigParkThrough configParkThrough,
                                                           HttpServletRequest req) {
        Result<List<ConfigParkThrough>> result = new Result<>();
        List<ConfigParkThrough> pageList;
        pageList = configParkThroughService.findConfigParkThroughByParkCode();
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @AutoLog(value = "指定车场入口车道列表查询")
    @ApiOperation(value = "指定车场入口车道列表查询", notes = "指定车场入口车道列表查询")
    @RequestMapping(value = "/ArmThroughData")
    public Result<ConfigParkThrough> armThroughData(ConfigParkThrough configParkThrough, HttpServletRequest req) {
        Result<ConfigParkThrough> result = new Result<ConfigParkThrough>();
        try {
            configParkThrough = configParkThroughService.queryConfigParkThrough(configParkThrough.getSerialNo());
            result.setResult(configParkThrough);
            return result;
        } catch (Exception e) {
            result.setCode(500);
            return result;
        }
    }

}
